'use strict'

const crypto = require('crypto')
const fs = require('fs')

let saltArr = [
  'a', 'b', 'c', 'd', 'e', 'f', 'g',
  'h', 'i', 'j', 'k', 'l', 'm', 'n',
  'o', 'p', 'q', 'r', 's', 't', 'u',
  'v', 'w', 'x', 'y', 'z', '1', '2',
  '3', '4', '5', '6', '7', '8', '9'
]

exports.randstr = function (length = 8) {

  let total = saltArr.length
  let saltstr = ''

  for (let i = 0; i < length; i++) {
    saltstr += saltArr[ parseInt(Math.random() * total) ]
  }

  return saltstr
}

exports.sha1 = (str, encoding = 'hex') => {
  let h = crypto.createHash('sha1')
  h.update(str)
  return h.digest(encoding)
}

exports.md5 = (str, encoding = 'hex') => {
  let h = crypto.createHash('md5')
  h.update(str)
  return h.digest(encoding)
}

exports.sha256 = (str, encoding = 'hex') => {
  let h = crypto.createHash('sha256')
  h.update(str)
  return h.digest(encoding)
}

exports.sha512 = (str, encoding = 'hex') => {
  let h = crypto.createHash('sha512')
  h.update(str)
  return h.digest(encoding)
}

exports.xssfilter = (data) => {
  return data.replace(/</ig, '&lt;')
            .replace(/>/ig, '&gt;');
}

exports.tryMkdir = async (dirname) => {
  let st = await new Promise((rv, rj) => {
    fs.access(dirname, err => {
      if (err) {
        rv(false)
      }
      rv(true)
    })
  })

  if (st === true) {
    return true
  }

  return await new Promise((rv, rj) => {
    fs.mkdir(dirname, err => {
      if (err) {
        rj(err)
      }
      rv(true)
    })
  })
}

let floatPreg = /^[0-9]+\.[0-9]+$/;

exports.floatPreg = floatPreg;

let intPreg = /^[0-9]+$/;

exports.intPreg = intPreg;
